const express = require('express');
const router = express.Router();
const { exec } = require('child_process');
const path = require('path');
const fs = require('fs');
const { isAdmin } = require('../middleware/roles');
const logger = require('../utils/logger');

// 创建备份目录
const backupDir = path.join(__dirname, '../backups');
if (!fs.existsSync(backupDir)) {
  fs.mkdirSync(backupDir);
}

// 数据库备份接口 - 仅管理员可用
router.post('/database', isAdmin, async (req, res) => {
  try {
    const date = new Date().toISOString().slice(0, 10);
    const backupFileName = `backup_${date}.sql`;
    const backupPath = path.join(backupDir, backupFileName);

    // 从数据库配置中获取信息
    const dbConfig = require('../config/db').pool.config;
    
    // 构建 mysqldump 命令
    const command = `mysqldump -h ${dbConfig.host} -u ${dbConfig.user} -p${dbConfig.password} ${dbConfig.database} > ${backupPath}`;

    exec(command, (error, stdout, stderr) => {
      if (error) {
        logger.error('数据库备份失败:', error);
        return res.status(500).json({
          success: false,
          error: '数据库备份失败',
          code: 500
        });
      }

      // 删除7天前的备份文件
      const files = fs.readdirSync(backupDir);
      const now = new Date();
      files.forEach(file => {
        const filePath = path.join(backupDir, file);
        const stats = fs.statSync(filePath);
        const days = (now - stats.mtime) / (1000 * 60 * 60 * 24);
        if (days > 7) {
          fs.unlinkSync(filePath);
          logger.info(`删除过期备份文件: ${file}`);
        }
      });

      res.json({
        success: true,
        data: {
          file_name: backupFileName,
          file_path: backupPath,
          file_size: fs.statSync(backupPath).size,
          created_at: new Date()
        },
        message: '数据库备份成功'
      });
    });
  } catch (error) {
    logger.error('备份过程出错:', error);
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

// 获取备份文件列表 - 仅管理员可用
router.get('/database/list', isAdmin, (req, res) => {
  try {
    const files = fs.readdirSync(backupDir)
      .filter(file => file.endsWith('.sql'))
      .map(file => {
        const filePath = path.join(backupDir, file);
        const stats = fs.statSync(filePath);
        return {
          file_name: file,
          file_size: stats.size,
          created_at: stats.mtime
        };
      })
      .sort((a, b) => b.created_at - a.created_at);

    res.json({
      success: true,
      data: files
    });
  } catch (error) {
    logger.error('获取备份列表失败:', error);
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

// 下载备份文件 - 仅管理员可用
router.get('/database/download/:filename', isAdmin, (req, res) => {
  try {
    const { filename } = req.params;
    const filePath = path.join(backupDir, filename);

    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        success: false,
        error: '备份文件不存在',
        code: 404
      });
    }

    res.download(filePath);
  } catch (error) {
    logger.error('下载备份文件失败:', error);
    res.status(500).json({
      success: false,
      error: error.message,
      code: 500
    });
  }
});

module.exports = router; 